<?php

namespace App\Http\Controllers\CRM;

use App\Enums\UserType;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\UserLevelRequest;
use App\Http\Resources\CRM\UserLevelResource;
use App\Levels\LevelFactory;
use App\Models\UserLevel;
use Illuminate\Http\Request;

class UserTypePointLevelController extends Controller
{
    public function getUserTypes()
    {
        $cases = UserType::cases();
        $res = [];
        foreach ($cases as $case) {
            $res[] = [
                'value' => $case->value,
                'label' => $case->label(),
            ];
        }

        return ApiResponseHelper::json($res);
    }

    public function getTypeLevel(UserType $type, LevelFactory $factory)
    {
        $userLevel = UserLevel::where('type', $type)->first();
        if (empty($userLevel)) {
            $userLevel = new UserLevel();
            $userLevel->type = $type;
            $userLevel->content = $factory->createLevel($type);
            $userLevel->save();
        }

        return new UserLevelResource($userLevel);
    }

    public function updateTypeLevel(UserType $type, UserLevelRequest $request)
    {
        $userLevel = UserLevel::where('type', $type)->first();

        $level = $userLevel->content;
        $level->setPoints($request->points);
        $level->setScopes($request->scopes);

        $userLevel->content = $level;
        $userLevel->save();

        return new UserLevelResource($userLevel);
    }
}
